<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;
use app\common\controller\Config;

class Address extends Base
{
    protected $name = 'user_address';

    public function p()
    {
        return $this->hasOne(Area::class, 'code', 'province')->field('code,province as title');
    }

    public function c()
    {
        return $this->hasOne(Area::class, 'code', 'city')->field('code,city as title');
    }

    public function d()
    {
        return $this->hasOne(Area::class, 'code', 'district')->field('code,district as title');
    }

    public function t()
    {
        return $this->hasOne(Area::class, 'code', 'town')->field('code,town as title');
    }


    public static function add($param, $user): array
    {
        try {
            $type = isset($param['type']) ? $param['type'] : '';
            if (isset($param['default']) && $param['default'] == 1) {
                parent::update(['default' => 0], ['uid' => $user->id]);
            }
            $code = 3;
            $url = '';
            $dq=explode('-',$param['classes']);
            $param['province']=$dq[0];
            $param['city']=$dq[1];
            $param['district']=$dq[2];
            
            unset($param['classes']);
            if (isset($param['id']) && $param['id']) {
                parent::update($param);
                $msg = '已修改';
            } else {
                $param['uid'] = $user->id;
                unset($param['type']);
                $new = parent::create($param);
                $msg = '已添加';
                if ($type == 'add') {
                    $code = 4;
                    Cache::set('choiceAddress_' . $user->id, $new->id);
                   // $url = url('order/index')->build();
                }
            }
            return ['code' => $code, 'msg' => $msg, 'url' => $url];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function edit($id, $user): array
    {
        try {
            $info = parent::where('id', $id)->find();
            if (empty($info) || $info->uid != $user->id) {
                return ['code' => -1, 'msg' => '加载失败，记录不存在'];
            }
            $info->is_del = 1;
            $info->save();
            return ['code' => 1, 'msg' => '已删除'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    //设置默认收货地址
    public static function chooseDefault($param, $user): array{

        try {
            parent::update(['default' => 0], ['uid' => $user->id]);
            $info = parent::where('id', $param['id'])->find();
            if (empty($info) || $info->uid != $user->id) {
                return ['code' => -1, 'msg' => '加载失败，记录不存在'];
            }
            if($param['type']==0){
                $info->default = 0;
                $msg='取消默认地址成功';
            }else{
                $info->default = 1;
                $msg='设置默认地址成功！';
            }
            $info->save();
            return ['code' => 1, 'msg' => $msg];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function getDefault($uid,$total,$products,$num)
    {
        try {
            $syytem=Config::lists();
            $cacheId = Cache::get('choiceAddress_' . $uid);
            $baoyous=self::getBaoyou($total,$products,$num);
            if ($cacheId) {
                $info = parent::where(['id' => $cacheId, 'is_del' => 0])->find();
                $info->provincename= Area::where(['code'=>$info->province])->value('province');
                $info->cityname= Area::where(['code'=>$info->city])->value('city');
                $info->districtname= Area::where(['code'=>$info->district])->value('district');
                if(count($baoyous) == array_sum($baoyous)){
                    $yunfei=0;
                }else{
                    $yunfei=Freight::where(['area_code'=>$info->province])->value('money');
                }
                $info->yunfei=$yunfei!='' ? $yunfei : 0;
                if ($info) return $info;
            
            }
            $info = parent::where(['uid' => $uid, 'is_del' => 0, 'default' => 1])->find();
            $info->provincename= Area::where(['code'=>$info->province])->value('province');
            $info->cityname= Area::where(['code'=>$info->city])->value('city');
            $info->districtname= Area::where(['code'=>$info->district])->value('district');
            if(count($baoyous) == array_sum($baoyous)){
                $yunfei=0;
            }else{
                $yunfei=Freight::where(['area_code'=>$info->province])->value('money');
            }
            $info->yunfei=$yunfei!='' ? $yunfei : 0;
            if ($info) return $info;

            $info = parent::where(['uid' => $uid, 'is_del' => 0])->order('update_time', 'desc')->find();
            $info->provincename= Area::where(['code'=>$info->province])->value('province');
            $info->cityname= Area::where(['code'=>$info->city])->value('city');
            $info->districtname= Area::where(['code'=>$info->district])->value('district');
            if(count($baoyous) == array_sum($baoyous)){
                $yunfei=0;
            }else{
                $yunfei=Freight::where(['area_code'=>$info->province])->value('money');
            }
            $info->yunfei=$yunfei!='' ? $yunfei : 0;
            
            if ($info) return $info;

            return '';
        } catch (\Exception $e) {
            return '';
        }
    }

    public static function choice($id, $user): array
    {
        Cache::set('choiceAddress_' . $user->id, $id);
        return ['code' => 1, 'msg' => '选择收货地址成功！'];
    }
    //判断是否包邮
    public static function getBaoyou($total,$products,$num): array
    { 
        foreach($products as $k=>$v){
            //订单满额
            if($v['rule_by']==1 && $v['rule_num']<=$total){
                $count=1;
            }else if($v['rule_by']==2 && $v['rule_num']<=$num){//订单满件
                $count=1;
            }else if($v['rule_by']==3 && $v['rule_num']<=($v['price'] * $v['num'])){ //单品满额
                $count=1;
            }elseif($v['rule_by']==4 && $v['rule_num']<= $v['num']){ //单品满额
                $count=1;
            }else{
                $count=0;
            }
            $countlist[]=$count;
        }
        return $countlist;
    }

}
